#!/usr/bin/python2.5
"""This is the main file for GeoTree demo.
It includes classes for the first page and to fetch JSON data for tile.
"""

__author__ = 'Artem Dudarev'
__licence__ = 'Apache 2.0'
__date__ = 'Thu 29 Apr 2010 02:20:45 PM EEST'

import os
import logging
import time

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from geotree.geotree import GeoTree, Point
import geotree.geohash as geohash


class InsertPoint(webapp.RequestHandler):
    def post(self):
        lat = self.request.get('lat').strip()
        lon = self.request.get('lng').strip()
        z = self.request.get('z').strip()
        # importance is sum of given importance 
        # and a number time.time()/2e9 < 1.0 until ~ year 2030
        # this way, a later submitted point with the same importance is slightly more important
        importance = float(self.request.get('importance').strip()) + time.time()/2e9
        coord = "%s,%s" % (lat,lon)
        # key_name should be an application specific, here it is 8 character 64 bit word
        p = Point(coord=coord,importance=importance,name='')
        p.put()
        GeoTree.insert_points_list([p], gt_key_name='points')
        GeoTree.update_tiles(15, gt_key_name='points')
        gt = GeoTree.get(gt_key_name='points')
        self.response.out.write('points - %s<br/>last tiles - %s' % (gt.number_points, gt.tiles_updated))


class GetTiles(webapp.RequestHandler):
    def get(self):
        center = self.request.get('c').strip()
        gt_key_name = self.request.get('gt').strip()
        tiles = GeoTree.fetch_around_tile(center, gt_key_name=gt_key_name)
        self.response.out.write(tiles);


class MainHandler(webapp.RequestHandler):
    def get(self):

        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path,{}))


application = webapp.WSGIApplication([
                                    ('/', MainHandler),
                                    ('/t/', GetTiles),
                                    ('/insert_point', InsertPoint),
                                    ],
                                   debug=True)

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
